package com.randy.fundation;


import com.randy.fundation.Logger;

import java.util.regex.Pattern;

public class RegexUtility {
    public static Pattern build(String text) {
        Pattern pattern = buildRegex(text);
        if (pattern == null) {
            pattern = buildNormal(text);
        }

        return pattern;
    }

    public static Pattern buildRegex(String text) {
        char[]        chars  = text.toCharArray();
        StringBuilder buffer = new StringBuilder(text.length() * 3);
        buffer.append(".*");
        char last = 0x00;
        for (char ch : chars) {
            if (ch == '.') {
                buffer.append(ch);
            } else if (ch == '*') {
                if (last == 0x00) {
                    buffer.append('.');
                    buffer.append(ch);
                } else {
                    buffer.append(ch);
                }
            } else {
                buffer.append(ch);
                buffer.append(".*");
            }
            last = ch;
        }

        Pattern pattern = null;

        try {
            pattern = Pattern.compile(buffer.toString(), Pattern.CASE_INSENSITIVE);
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }

        return pattern;
    }

    public static Pattern buildNormal(String text) {
        char[]        chars  = text.toCharArray();
        StringBuilder buffer = new StringBuilder(text.length() * 3);
        buffer.append(".*");
        for (char ch : chars) {
            if (ch == '.') {
                buffer.append("\\");
                buffer.append(ch);
            } else if (ch == '*') {
                buffer.append("\\");
            } else {
                buffer.append(ch);
            }
            buffer.append(".*");
        }

        Pattern pattern = null;

        try {
            pattern = Pattern.compile(buffer.toString(), Pattern.CASE_INSENSITIVE);
        } catch (Exception e) {
            Logger.e(e.getMessage());
        }

        return pattern;
    }
}
